package wang.chunfan.code.websocket.client;


import com.alibaba.fastjson.JSON;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.util.UriBuilder;
import wang.chunfan.code.websocket.model.Message;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class MyWebSocketClient extends WebSocketClient {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyWebSocketClient.class);

    public MyWebSocketClient(URI serverUri) {
        super(serverUri);
    }

    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        LOGGER.info("open ...");
    }

    @Override
    public void onMessage(String s) {
        LOGGER.info("message:{}", s);
    }

    @Override
    public void onClose(int i, String s, boolean b) {
        LOGGER.info("close");
    }

    @Override
    public void onError(Exception e) {
        LOGGER.error("error...{}", e.getMessage());
    }

    public static void main(String[] args) throws Exception {

        ThreadPoolExecutor pool = new ThreadPoolExecutor(500, 2000, 0, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>());

        for (int i = 0; i < 11; i++) {

            URI uri = new URI("ws://localhost:8080//webSocket/" + i);

            pool.execute(() -> {

                MyWebSocketClient client = new MyWebSocketClient(uri);
                boolean result = false;
                try {
                    result = client.connectBlocking();
                    if (result == false) {
                        System.out.println("连接失败！");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Message message = new Message();
                message.setType("single");
                message.setData("你好");

                client.send(JSON.toJSONString(message));
            });
            Thread.sleep(100);
        }


    }
}
